const Model = require('../models/config-model')
const ResponseModel = require('../models/response-model')
const baseConfig = require('../base-config')
const SystemConfig = require('../utils/system-config')

// const fs = require('fs')
const { spawnSync, spawn } = require('child_process');

const { readRemoteFile } = require('../utils/common');

function wrapConfig(config) {
    delete config.version // 以version文件为准
    const exposeConfig = {
        ...baseConfig,
        ...config,
        passkey: '******'
    }
    return exposeConfig
}

module.exports = {
    // 
    'get::/config/get': async (ctx) => {
        ctx.response.body = ResponseModel.success(wrapConfig(await SystemConfig.me()))
    },
    //
    'post::/config/set': async (ctx) => {
        const params = ctx.request.body
        if (params) {

            const rows = await Model.updateBy(params , { tag: 'system' });

            // 清除缓存,获取实例
            const systemConfig = await SystemConfig.me(true);

            if (params.notify) {
                // 配置通知
                require('../utils/notify').setup(systemConfig.notify);
            }
            if (params.tmdb) {
                // 配置tmdb
                require('../utils/media-netdata/tmdb').setup(systemConfig.tmdb);
            }
            if (params.jellyfin) {
                // 配置jellyfin
                require('../utils/media-server/jellyfin-server').setup(systemConfig.jellyfin);
            }

            ctx.response.body = ResponseModel.success(wrapConfig(systemConfig))
            return
        }
        ctx.response.body = ResponseModel.failure('参数错误')
    },
    // 
    'get::/config/checkUpdate': async (ctx) => {
        const version = await readRemoteFile('https://gitee.com/523757325/torrent-manager-node/raw/master/src/.version')
        ctx.response.body = ResponseModel.success({ version: version })
    },
    // 
    'get::/config/doUpdate': async (ctx) => {

        const {restart} = ctx.request.query

        const cp = spawnSync('/app/shell/update.sh', // /app/shell/update.sh
            { 
                shell: true,
                encoding: 'utf8',
            }
        );
        let log = '';
        log += `[STDOUT]: ${cp.stdout}\n`;
        log += `[STDERR]: ${cp.stderr}\n`;
        log += `[ERROR]: ${cp.error}\n`;
        log += `[EXIT-CODE]: ${cp.status}\n`;

        // 1秒后重启
        if (restart) {
            setTimeout(() => {
                spawn('/app/shell/update.sh restart',
                    { 
                        shell: true
                    }
                )
            }, 1000);
        }
        
        ctx.response.body = ResponseModel.success(log);
    },
    // 
    'get::/config/restart': async (ctx) => {
        spawn('/app/shell/update.sh restart',
            { 
                shell: true
            }
        );
        ctx.response.body = ResponseModel.success();
    },
    
}
  